<?php

namespace app\admin\controller\tuan;

use app\admin\model\Autonym;
use app\admin\model\Card;
use app\admin\model\Consume;
use app\common\controller\Backend;
use think\Cache;
use think\Controller;
use think\Db;
use think\Request;
use think\Exception;

/**
 * 
 *
 * @icon fa fa-circle-o
 */
class Depositlist extends Backend
{
    
    /**
     * Depositlist模型对象
     */
    protected $model = null;
    protected $relationSearch = true;
    protected $modelValidate = true;
    protected $multiFields = "finance_status";

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Depositlist');

    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个方法
     * 因此在当前控制器中可不用编写增删改查的代码,如果需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 列表
     */
    public function index()
    {
        return $this->view->fetch();
    }

    /*
     */
    public function table1(){
        set_time_limit(0);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where)
                ->where(['delete_status'=>1])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->field('depositlistID,cardID,consumeID,userID,time,status,f_id,audit_time,rake_price,type,bank_tradeno,pay_account_id,finance_status,finance_note,remit_time,reject_time,operation_time,bank_no_num')
                ->where($where)
                ->where(['delete_status'=>1])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $Card = new Card();
            $Consume = new Consume();

            foreach ($list as $k=>$v){
                //处理单号
                $arr = explode('-',$v['bank_tradeno']);
                $list[$k]['bank_tradeno'] = $arr;
                //银行卡信息
                $card = $Card->get($v['cardID']);
                $list[$k]['bank'] = $card['bank'].$card['branch_bank'];
                $list[$k]['name'] = $card['name'];
                $list[$k]['number'] = $card['number'];
                $list[$k]['location'] = $card['location'];
                //打款金额
                $consume = $Consume->get($v['consumeID']);
                $money = bcsub($consume['fees'],$v['rake_price']);
                $list[$k]['money'] = bcdiv($money,100,2);
                $list[$k]['rake_price'] = bcdiv($v['rake_price'],100,2);
                //操作人
                $list[$k]['operator'] = Db::name('admin_fast')->where('id',$v['f_id'])->value('username');
            }

            //统计
            $str1 = md5($this->request->get("filter", ''));
            if (Cache::get($str1) == false) {
                $sum = Db::name('depositlist')
                    ->alias('depositlist')
                    ->join('dy_consume consume1','depositlist.consumeID = consume1.consumeID')
                    ->field('sum(fees) sum1,sum(rake_price) sum2')
                    ->where($where)
                    ->where(['delete_status'=>1])
                    ->cache($str1,90)
                    ->select();
            } else {
                $sum  = Cache::get($str1);
            }

            $out_total = bcsub($sum[0]['sum1'],$sum[0]['sum2']);
            $out_total = bcdiv($out_total,100,2);
            $rake_price = bcdiv($sum[0]['sum2'],100,2);

            $result = array("total" => $total, "rows" => $list,"extend"=>['out_total'=>$out_total,'rake_price'=>$rake_price]);

            return json($result);
        }
//        return $this->view->fetch();
    }

    public function table2(){
        set_time_limit(0);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('pkey_name'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = $this->model
                ->with([
                    'user'=>function($query){
                        $query->where('status','=',1)->withField('account,phone,status');
                    }
                ])
                ->where($where)
                ->where(['delete_status'=>1])
                ->order($sort, $order)
                ->count();

            $list = $this->model
                ->field('depositlistID,cardID,consumeID,userID,time,status,f_id,audit_time,rake_price,type,bank_tradeno,pay_account_id,finance_status,finance_note,remit_time,reject_time,operation_time,bank_no_num')
                ->with([
                    'user'=>function($query){
                        $query->where('status','=',1)->withField('account,phone,type');
                    }
                ])
                ->where($where)
                ->where(['delete_status'=>1])
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();

            $Card = new Card();
            $Consume = new Consume();

            foreach ($list as $k=>$v){
                if($v['user']['type'] == '商家'){
                    $list[$k]['account_type'] = 1;
                }else{
                    $list[$k]['account_type'] = 2;
                }
                //处理单号
                $arr = explode('-',$v['bank_tradeno']);
                $list[$k]['bank_tradeno'] = $arr;
                //银行卡信息
                $card = $Card->get($v['cardID']);
                $list[$k]['bank'] = $card['bank'].$card['branch_bank'];
                $list[$k]['name'] = $card['name'];
                $list[$k]['number'] = $card['number'];
                $list[$k]['location'] = $card['location'];
                //打款金额
                $consume = $Consume->get($v['consumeID']);
                $money = bcsub($consume['fees'],$v['rake_price']);
                $list[$k]['money'] = bcdiv($money,100,2);
                $list[$k]['rake_price'] = bcdiv($v['rake_price'],100,2);
                //操作人
                $list[$k]['operator'] = Db::name('admin_fast')->where('id',$v['f_id'])->value('username');
            }

            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
//        return $this->view->fetch();
    }

    /**
     * 详情
     * @param int   $ids
     * @return mixed
     */
    public function details($ids = 0){
        $deposit = $this->model
            ->field('depositlistID,cardID,consumeID,userID,time,status,id,audit_time,rake_price,type,bank_tradeno,pay_account_id,finance_status,finance_note,remit_time,reject_time,operation_time')
            ->with([
            'user'=>function($query){
                $query->where('status','=',1)->withField('account,phone');
            }
        ])->where('depositlistID',$ids)->find();

        $Card = new Card();
        $Consume = new Consume();


        if($deposit['finance_status'] < 3)
            $this->error('该记录状态已发生变化');

        //银行卡信息
        $card = $Card->get($deposit['cardID']);
        $deposit['name'] = $card['name'];
        $deposit['number'] = $card['number'];
        $deposit['bank'] = $card['bank'];
        $deposit['branch_bank'] = $card['branch_bank'];
        $deposit['location'] = $card['location'];
        //打款金额
        $consume = $Consume->get($deposit['consumeID']);
        $money = bcsub($consume['fees'],$deposit['rake_price']);
        $deposit['money'] = bcdiv($money,100,2);
        $deposit['fees'] = bcdiv($consume['fees'],100,2);
        $deposit['rake_price'] = bcdiv($deposit['rake_price'],100,2);

        $arr = [3=>'待打款',4=>'打款失败',5=>'打款成功',6=>'银行驳回',7=>'到账成功'];
        $type = [1=>'手动提现',2=>'自动提现'];
        $deposit['finance_status1'] = $arr[$deposit['finance_status']];
        $deposit['type'] = $type[$deposit['type']];
        $deposit['bank_tradeno'] = explode('-',$deposit['bank_tradeno']);
        $this->view->assign("row", $deposit);
        return $this->view->fetch();
    }

    /**
     * 编辑
     * @param int   $ids
     * @param int   $type
     * @return mixed
     */
    public function edit($ids = 0,$type=0){
        $row = $this->model->get($ids);
        if (!$row)
            $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds))
        {
            if (!in_array($row[$this->dataLimitField], $adminIds))
            {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost())
        {
            $this->request->filter(['trim']);
            $params = $this->request->post("row/a");
            if ($params)
            {
                $time = time();
                $f_id = session('admin.id');
                if($params['act'] == 'edit'){//待打款时的操作
                    if($row['finance_status'] != 3)
                        $this->error('该记录已处理');
                    try
                    {
                        //是否采用模型验证
                        if ($this->modelValidate)
                        {
                            $name = basename(str_replace('\\', '/', get_class($this->model)));
                            $validate = $name.'.edit';
                            $row->validate($validate);
                        }

                        if($params['finance_status'] == 5){
                            $num = count($params['bank_tradeno']);
                            $params['bank_no_num'] = $num;
                            if($num != count(array_unique($params['bank_tradeno'])))
                                $this->error('请不要重复填同一单号');

                            $bank_tradeno = join('-',$params['bank_tradeno']);
                            $params['bank_tradeno'] = $bank_tradeno;
                            if(empty($bank_tradeno))
                                $this->error('请填写打款单号');
                            if(empty($params['pay_account_id']))
                                $this->error('请选择出款账户');
                        }

                        if($params['finance_status'] == 4 && empty($params['finance_note']))
                            $this->error('请填写备注');

                        $params['remit_time'] = $time;
                        $params['f_id'] = $f_id;
                        $result = $row->allowField(true)->save($params);
                        if ($result !== false)
                        {
                            $this->success();
                        }
                        else
                        {
                            $this->error($row->getError());
                        }
                    }
                    catch (\think\exception\PDOException $e)
                    {
                        $this->error($e->getMessage());
                    }
                }elseif($params['act'] == 'audit'){//打款成功时的操作
                    if($row['finance_status'] != 5)
                        $this->error('该记录已处理');
                    Db::startTrans();
                    try
                    {
                        //是否采用模型验证
                        if ($this->modelValidate)
                        {
                            $name = basename(str_replace('\\', '/', get_class($this->model)));
                            $validate = $name.'.audit';
                            $row->validate($validate);
                        }
                        if($params['finance_status'] == 6 && empty($params['finance_note']))
                            $this->error('请填写驳回原因');

                        $params['reject_time'] = $time;
                        $result = $row->allowField(true)->save($params);
                        if ($result === false)
                        {
                            throw new Exception($row->getError());
                        }

                        //审核通过的业务操作
                        if($params['finance_status'] == 7){
                            $data = [
                                'status'=>3,
                                'note'=>'通过',
                                'audit_time'=>$time,
                                'f_id'=>$f_id
                            ];
                            $this->model->where('depositlistID',$params['depositlistID'])->update($data);

                            Db::name('consume')->where('consumeID',$row['consumeID'])->update(['status'=>2]);
                        }

                        Db::commit();
                        $this->success();
                    }
                    catch (Exception $e)
                    {
                        Db::rollback();
                        $this->error($e->getMessage());
                    }
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        if($type){
            return $this->view->fetch('audit');
        }else{
            return $this->view->fetch();
        }
    }

    /**
     * 批量更新
     */
    public function multi($ids = "")
    {
        $ids = $ids ? $ids : $this->request->param("ids");
        if ($ids)
        {
            if ($this->request->has('params'))
            {
                parse_str($this->request->post("params"), $values);
                $values = array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
                if ($values)
                {
                    $adminIds = $this->getDataLimitAdminIds();
                    if (is_array($adminIds))
                    {
                        $this->model->where($this->dataLimitField, 'in', $adminIds);
                    }
                    $time = time();
                    $values['status'] = 3;
                    $values['note'] = '通过';
                    $values['audit_time'] = $time;
                    $values['reject_time'] = $time;
                    $values['f_id'] = session('admin.id');
                    $count = $this->model->where($this->model->getPk(), 'in', $ids)->update($values);
                    $consumeIds = $this->model->where($this->model->getPk(), 'in', $ids)->column('consumeID');
                    Db::name('consume')->where(['consumeID'=>['in',$consumeIds]])->update(['status'=>2]);
                    if ($count)
                    {
                        $this->success();
                    }
                    else
                    {
                        $this->error(__('更新失败，请重试'));
                    }
                }
                else
                {
                    $this->error(__('You have no permission'));
                }
            }
        }
//        $this->error(__('Parameter %s can not be empty', 'ids'));
        $this->error(__('请选择要更新的序号'));
    }
}
